/**
 * 订单推送客户端
 * usage:
 *   var a = new OrderPushClient();
 *   a.start();
 *   a.on('orderCreated', function (e) {
 *     console.log(e.data.order_id);
 *   });
 *  停止:
 *     a.stop();
 */
function OrderPushClient() {
  this.config = this.default_config;
  // 监听者
  this.listeners = {

  };
  // websocket 客户端
  this.ws = null;
  // 心跳interval id
  this.heartBeatId = null;
}

OrderPushClient.prototype.default_config = {
  host: '47.91.72.8',
  port: '31675'
};

OrderPushClient.prototype.on = function (event_name, handler) {
  if (!this.listeners.hasOwnProperty(event_name)) {
    this.listeners[event_name] = [];
  }

  this.listeners[event_name].push(handler);
};

OrderPushClient.prototype.connect = function () {
  this.ws = new WebSocket('ws://'+this.config.host+':'+this.config.port);
};

OrderPushClient.prototype.heartBeat = function () {
  if (null === this.ws) {
    throw new Error('webSocket not connect');
  }

  this.ws.onerror = (function () {
    clearInterval(this.heartBeatId);
  }).bind(this);

  var call = function () {
    this.ws.send(JSON.stringify({
        'method': 'get',
        'route': '/client/heartBeat',
        'request': {
        }
    }));
  };
  setInterval(call.bind(this), 5000);
};

// 解析message 分发事件
OrderPushClient.prototype.parsedMessage = function () {
  this.ws.onmessage = (function (e) {
    try {
      var data = JSON.parse(e.data);
    } catch (e) {
      throw e;
    }
    var eventName = data.event;
    var payload = data.payload;
    var event = {
      eventName: eventName,
      data: payload,
      ws: this.ws
    };
    if (this.listeners.hasOwnProperty(eventName)) {
      for(var k in this.listeners[eventName]) {
        let handler = this.listeners[eventName][k];
        handler(event);
      }
    }
  }).bind(this);
};

OrderPushClient.prototype.start = function () {
  this.connect();
  this.parsedMessage();
  this.heartBeat();
};

OrderPushClient.prototype.stop = function () {
  this.ws.close();
};
